﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using AcctrueWMS.Foundation.Data;
using AcctrueWMS.Foundation.Web;
using System.Web;
using AcctrueWMS.Foundation.DAL;
using AcctrueWMS.Foundation.Web.Session;
using AcctrueWMS.Foundation.Util;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Common;
using AcctruePMS.Bll.Common;
using AcctrueWMS.Foundation.Common.Exception;
namespace AcctruePMS.Bll.Manager
{
    public class UserManager
    {
    
        /// <summary>
        /// 验证session
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="passport">加密后的密码</param>
        /// <param name="logMessage">提示信息</param>
        /// <returns>bool</returns>
        public SystemUser ValidateLoginToGetUser(string userName, string passport, out string logMessage)
        {
            logMessage = string.Empty;
            SystemUser currUser = null;
            string QueryStr = DBFactory.NewQueryStr("select * from userInfo where userName=@usname and password=@pwd ");

            DataTable dtUserInfo = WMSqlExcuter.ExecuteDataTable(QueryStr,CommandType.Text,
                DBFactory.NewParameter("pwd", passport), DBFactory.NewParameter("usname", userName));       

            if (dtUserInfo.Rows.Count > 0)
            {
                currUser = GetUserInfo(dtUserInfo);
            }
            else
            {
                logMessage = "用户名或密码不正确，登陆失败！";
            }
            return currUser;

        }
        /// <summary>
        /// 获取当前登录用户信息:用户名 用户编号 显示名 岗位编号
        /// </summary>
        /// <param name="model"></param>
        private SystemUser GetUserInfo(DataTable currentUser)
        {
            string userNo = currentUser.Rows[0]["userNo"].ToString();
            DataTable userRoles = WMSqlExcuter.ExecuteDataTable(string.Format("select roleCode from userRoleInfo where userNo='{0}'", userNo));

            StringBuilder rolesJoint = new StringBuilder();

            for (int i = 0; i < userRoles.Rows.Count; i++)
            {
                rolesJoint.Append(userRoles.Rows[i]["roleCode"].ToString() + ",");
            }
            if (rolesJoint.Length > 0)
            {
                rolesJoint.Remove(rolesJoint.Length - 1, 1);
            }
            return new SystemUser()
            {
                DisplayName = currentUser.Rows[0]["displayName"].ToString(),
                RoleCodes = rolesJoint.ToString(),
                UserName = currentUser.Rows[0]["userName"].ToString(),
                UserNo = currentUser.Rows[0]["userNo"].ToString()

            };
        }

        /// <summary>
        /// 得到所有用户的信息，key:userNo,value:displayName
        /// </summary>
        /// <returns></returns>
        public DataTable GetAllUserInfoAsDict()
        {
            string cmdText = "select userNo as [key],userName+'('+displayName+')'  as [value] from userInfo ";
            return WMSqlExcuter.ExecuteDataTable(cmdText);
        }

     
        /// <summary>
        /// 通过用户编码得到用户名
        /// </summary>
        /// <param name="userNo"></param>
        /// <returns></returns>
        public string GetUserNameByCode(string userNo)
        {
            return (string)WMSqlExcuter.ExecuteRealScalar(string.Format("select userName from userInfo where userNo='{0}'", userNo));
        }

        /// <summary>
        /// 通过用户编码得到显示名
        /// </summary>
        /// <param name="userNo"></param>
        /// <returns></returns>
        public string GetDisplayNameByCode(string userNo)
        {
            return (string)WMSqlExcuter.ExecuteRealScalar(string.Format("select displayName from userInfo where userNo='{0}'", userNo));
        }


        //卸载当前用户的session
        public void UnloadCurrentUser()
        {
            System.Web.HttpContext.Current.Session.Abandon();
            System.Web.HttpContext.Current.Session.Clear();
        }



        /// <summary>
        /// 校验原密码是否正确
        /// </summary>
        /// <param name="oldPassword">原密码</param>
        /// <returns>false 表示校验失败  true 表示校验成功</returns>
        public string CheckOldPassword(string oldPassword)
        {
            string rtn = "false";
            if (string.IsNullOrEmpty(oldPassword)) return rtn;
            string userNo = System.Web.HttpContext.Current.Session[SessionConst.UserNo] != null ? System.Web.HttpContext.Current.Session[SessionConst.UserNo].ToString() : string.Empty;
            if (string.IsNullOrEmpty(userNo))
            {
                throw new WMSBllException("操作超时，请重新登录！");
            }
            oldPassword = AcctruePMS.Bll.Common.DateHelper.UnEscape(oldPassword);
            string md5Password = AuthHelper.Encrpt(oldPassword);   //加密密码
            int icount = Convert.ToInt32(WMSqlExcuter.ExecuteScalar("select count(1)  from userInfo where password=@password and userNo=@userNo ",
                 CommandType.Text,
                 DBFactory.NewParameter("password", md5Password), DBFactory.NewParameter("userNo", userNo)));
            if (icount > 0)
            {
                rtn = "true";
            }
            return rtn;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="express"></param>
        /// <returns></returns>
        public string GetEnCodePassWord(string express)
        {
            string rtn = "";
            if (string.IsNullOrEmpty(express)) return rtn;
            return AuthHelper.Encrpt(express);   //加密密码
        }
        /// <summary>
        /// 重置用户密码
        /// </summary>
        /// <param name="userNo">用户编码</param>
        /// <returns>true:重置成功  false:重置失败</returns>
        public string RecoveryPassword(string userNo)
        {
            string rtn = "false";
            if (string.IsNullOrEmpty(userNo)) return rtn;
            string defaultPassword = DataChecker.CheckForNull(WMSqlExcuter.ExecuteScalar("select settingValue from sys_settings where settingKey=@settingKey",
              CommandType.Text, DBFactory.NewParameter("settingKey", "defaultPassword")));
            if (defaultPassword == "")
            {
                throw new WMSBllException("系统未配置初始密码项！");
                return rtn;
            }
            try
            {
                string password = AuthHelper.Encrpt(defaultPassword); //加密密码
                WMSqlExcuter.ExecuteScalar("update userInfo set password=@password where userNo=@userNo ",
                     CommandType.Text,
                     DBFactory.NewParameter("password", password),
                     DBFactory.NewParameter("userNo", userNo));
                rtn = "true";
                return rtn;
            }
            catch (Exception)
            {
                return rtn;
            }
        }

        public string GetUserRoleCondition()
        {
            string userNo;
            userNo = System.Web.HttpContext.Current.Session[SessionConst.UserNo].ToString();
            return "createBy like '" + userNo + "'";
        }
    }
}
